package org.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        nativeQuery(em,"SHOW TABLES");
        nativeQuery(em,"SHOW COLUMNS FROM DEPARTMENT");
        nativeQuery(em,"SHOW COLUMNS FROM PERSON");
        persistEntity(em);
        nativeQuery(em,"SELECT * FROM DEPARTMENT");
        nativeQuery(em,"SELECT * FROM PERSON");
        em.close();
    }
    private static void persistEntity(EntityManager em){
        Department department = new Department();
        department.setName("Design");
        Person p1 = new Person("John",20);
        p1.setDepartment(department);
        Person p2 = new Person("Tom",12);
        p2.setDepartment(department);
        Person p3 = new Person("Jack",50);
        p3.setDepartment(department);
        department.setPersons(Arrays.asList(p1,p2,p3));
        em.getTransaction().begin();
        em.persist(p1);
        em.persist(p2);
        em.persist(p3);
        em.persist(department);
        em.getTransaction().commit();
    }
    private static void nativeQuery(EntityManager em,String s){
        System.err.println("-------------" + s + "----------------");
        Query query = em.createNativeQuery(s);
        List list = query.getResultList();
        for (Object o : list) {
            if (o instanceof Object[]) {
                System.err.println(Arrays.toString((Object[])o));
            }else{
                System.err.println(o);
            }
        }
    }
}
